package com.unience.ec2.eclipse;

import java.util.List;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.ui.application.ActionBarAdvisor;
import org.eclipse.ui.application.IActionBarConfigurer;
import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
import org.eclipse.ui.application.WorkbenchWindowAdvisor;

import com.unience.ec2.eclipse.config.Config;
import com.unience.ec2.eclipse.config.UtilSWT;
import com.unience.ec2.eclipse.config.account.Account;
import com.unience.ec2.eclipse.config.account.AccountManager;
import com.unience.ec2.eclipse.dialog.GetAccountDialog;
import com.unience.ec2.eclipse.dialog.NewAccountDialog;

public class ApplicationWorkbenchWindowAdvisor extends WorkbenchWindowAdvisor {

	public ApplicationWorkbenchWindowAdvisor(
			IWorkbenchWindowConfigurer configurer) {
		super(configurer);
	}

	public ActionBarAdvisor createActionBarAdvisor(
			IActionBarConfigurer configurer) {
		return new ApplicationActionBarAdvisor(configurer);
	}

	public void preWindowOpen() {
		IWorkbenchWindowConfigurer configurer = getWindowConfigurer();
		configurer.setInitialSize(new Point(1024, 800));
		configurer.setShowCoolBar(true);
		configurer.setShowStatusLine(false);

		Account account = loadAccount();
		Config config = null;
		if (account != null) {

			config = Config.getInstance(account.getKey(), account
					.getSecret(), account.getOwnerId(), AccountManager.ACCOUNTS_DIR);
		}
		else{
			config = Config.getInstance();
			
		}
	
		config.setDisplay(UtilSWT.getDisplay());

	}

	private Account loadAccount() {
		Account ret = null;

		AccountManager accountManager = new AccountManager();

		List<Account> accountList = accountManager.getAccountList();

		if (!accountList.isEmpty()) {

			GetAccountDialog inst = new GetAccountDialog(UtilSWT.getShell(),
					SWT.CENTER);

			inst.open();

			if (inst.isAccept()) {

				ret = inst.getAccount();

			} else {
				ret = null;
			}
		} else {

			NewAccountDialog inst = new NewAccountDialog(UtilSWT.getShell(),
					SWT.CENTER);

			inst.open();

			if (inst.isAccepted()) {

				Account account = new Account();

				account.setName(inst.getName());
				account.setKey(inst.getKey());
				account.setSecret(inst.getSecret());
				account.setOwnerId(inst.getOwnerID());
				accountManager.addAccount(account);

				ret = account;

			}

		}

		return ret;

	}

}
